package vn.smartoffice.promail.controller.dialog;

import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import org.zkoss.zul.Window;

import vn.smartoffice.auth.UserService;
import vn.smartoffice.promail.dto.MailContactGroupNode;
import vn.smartoffice.promail.entity.MailContactGroup;
import vn.smartoffice.promail.services.MailContactGroupService;

@VariableResolver(DelegatingVariableResolver.class)
public class ContactGroupDialogCtr {

	@WireVariable
	private MailContactGroupService mailContactGroupService;
	@WireVariable
	private UserService userService;

	private MailContactGroupNode node;
	private MailContactGroup chidlFolder;
	private boolean isCreateFolder;

	public MailContactGroupNode getNode() {
		if (isCreateFolder) {
			return new MailContactGroupNode(chidlFolder);
		} else {
			return node;
		}
	}

	@Wire
	private Window contactGroupDialog;

	@AfterCompose
	public void afterCompose(@ContextParam(ContextType.VIEW) Component view,
			@ExecutionArgParam("node") MailContactGroupNode node,
			@ExecutionArgParam("isCreateFolder") boolean isCreateFolder) {
		Selectors.wireComponents(view, this, false);
		this.node = node;
		this.isCreateFolder = isCreateFolder;
		if (isCreateFolder) {
			chidlFolder = new MailContactGroup();
		}
	}

	@Command("save")
	public void save() {
		chidlFolder.setUser(userService.getCurrentUser());
		chidlFolder.setOpen(false);
		if (node.getData() == null) {
			chidlFolder.setParentId(null);
		} else {
			chidlFolder.setParentId(node.getId());
			node.getData().setOpen(true);
			mailContactGroupService.update(node.getData());
		}

		mailContactGroupService.save(chidlFolder);
		contactGroupDialog.detach();
		BindUtils.postGlobalCommand(null, null, "refreshMailContactGroup", null);
	}

	@Command("update")
	public void update() {
		mailContactGroupService.update(node.getData());
		contactGroupDialog.detach();
		BindUtils.postGlobalCommand(null, null, "refreshMailContactGroup", null);
	}

	@Command("cancel")
	public void cancel() {
		contactGroupDialog.detach();
	}

	@Command("controlSaveOrCancel")
	public void controlSaveOrCancel() {
		if (isCreateFolder) {
			save();
		} else {
			update();
		}
	}

}
